package com.wuchengdong.web.extend.auth;

import com.wuchengdong.web.pojo.User;
import jakarta.annotation.PostConstruct;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import static com.wuchengdong.web.extend.utils.ValidateCodeOrTokenUtils.generateToken;

@Component
public class MysqlAuthHandler implements AuthHandler {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @PostConstruct
    private void postConstruct() {
        String create_table_sql = """
                        create table if not exists Auth
                         (
                             token   varchar(32) not null,
                             id varchar(20) not null,
                             constraint Auth_pk
                                 primary key (token)
                         );
                        """;
        this.jdbcTemplate.execute(create_table_sql);
    }

    @Override
    public String saveNewTokenWithUser(User user) {
        jdbcTemplate.update("delete from Auth where id = ?", user.getId());
        String sql =  "insert into Auth (token, id) values (?, ?)";
        String token = generateToken(32);
        jdbcTemplate.update(sql, token, user.getId());
        return token;
    }

    @Override
    public void cleanTokenWithUser(String token,int id) {
        jdbcTemplate.update("delete from Auth where token = ? or id = ?", token, id);
    }

    @Override
    public int getUserByToken(String token) {
        String sql = "select id from Auth where token = '" + token + "'";
        Integer integer = jdbcTemplate.queryForObject(sql, Integer.TYPE);
        return integer == null ? -1 : integer;
    }

    @Override
    public boolean checkToken(String token,User user) {
        String sql = "select token from Auth where token = ? and id = ?";
        return jdbcTemplate.queryForObject(sql, String.class, token, user.getId()) != null;
    }

    @Data
    class Auth {
        String id;
        String token;
    }
}
